//
//  JMCustomCell.m
//  NewiOSProject
//
//  Created by apple on 2023/11/29.
//  Copyright © 2023 范智渊. All rights reserved.
//

#import "JMCustomCell.h"
#import "UIView+PopupProtocol.h"
#import "DDPhotoViewController.h"
#import <ContactsUI/ContactsUI.h>
#import "JMSlicenseVC.h"

@interface JMCustomCell()<UITextFieldDelegate,CNContactViewControllerDelegate,CNContactPickerDelegate>
@property(nonnull, strong)UILabel *topTitle;

@property(nonnull, strong)UILabel *titleLab;
@property(nonnull, strong)UILabel *subTitle;

@property(nonnull, strong)UIView *ktpView;

@property(nonnull, strong)UIView *inputContentV;

@property(nonnull, strong)UIImageView *idcardBgImgV;
@property(nonnull, strong)UIImageView *successImgV;

@property(nonnull, strong)UIButton *rightArrowBtn;
@property(nonnull, strong)UILabel *leftTitleLab;
@property(nonnull, strong)UILabel *errorLab;
@property(nonnull, strong)UILabel *LineV;


@property(nonatomic, strong) CNContactPickerViewController *contactPickerViewController;
/// 选择了联系人回调
@property(nonatomic, copy) void(^didSelectedContact)(CNContact *contact);
@property (nonatomic, strong)CNContact *currentContact;//多个电话号码时使用
@property (nonatomic, strong)NSString *selPhoneNumber;//多个电话号码时使用
@end
CGFloat space = 24;
CGFloat topSpace = 16;

@implementation JMCustomCell
-(instancetype)initWithModel:(JMAuthCellModel *)model{
    if (self = [super init]) {
        [self setModel:model];
    }
    return self;
}

-(void)setModel:(JMAuthCellModel *)model{
    _model = model;
    @weakify(self);
    CGFloat top = 0;
    CGFloat left = 0;
    CGFloat right = 0;
    
    if (model.topTitle.length) {
        _topTitle = [JMControl createLabelWithFrame:(CGRectMake(space, topSpace, kAppW()-space*2, 24)) Font:fontWithWeight(17, UIFontWeightMedium) Text:model.topTitle color:HexAlpha_Str_COLOR(@"#222222", 1)];
        [self addSubview:_topTitle];
        top = _topTitle.bottom+16;
    }
    if ([model.title isEqualToString:@"Foto vivo"]) {
        _idcardImgV = [[UIImageView alloc]initWithFrame:(CGRectMake(0, 52, 168, 168))];
        _idcardImgV.image = ImageNamed(@"auth_liveness_bg");
        _idcardImgV.centerX= kAppW()/2;
        [self addSubview:_idcardImgV];
        
        _idcardBgImgV = [[UIImageView alloc]initWithFrame:(CGRectMake(0, 0, 140, 140))];
        _idcardBgImgV.cornerRadius = 70;
        _idcardBgImgV.top = _idcardImgV.top;
        _idcardBgImgV.centerX = kAppW()/2;
        _idcardBgImgV.backgroundColor = Hex_Str_COLOR(@"#F6F9FE");
        _idcardBgImgV.layer.borderColor=Hex_Str_COLOR(@"#C5CDFD").CGColor;
        _idcardBgImgV.layer.borderWidth = 4;
        [_idcardBgImgV setImage:ImageNamed(@"auth_camera_center")];
        _idcardBgImgV.contentMode = UIViewContentModeCenter;
        
        [self addSubview:_idcardBgImgV];
        [_idcardImgV tapAction:^(UIView *sender) {
            @strongify(self);
            [self check];
        }];
        _titleLab = [JMControl createLabelWithFrame:(CGRectMake(0, _idcardImgV.bottom+5, kAppW(), FontH(15))) Font:Font(15) Text:model.title color:Hex_Str_COLOR(@"#ffffff")];
        [self addSubview:_titleLab];
        _titleLab.textAlignment = 1;
        
        _subTitle = [JMControl createLabelWithFrame:(CGRectMake(0, _idcardImgV.bottom+5, kAppW(), FontH(15))) Font:Font(14) Text:model.placeHolder color:Hex_Str_COLOR(@"#555555")];
        _subTitle.height = 40;
        _subTitle.textAlignment = 1;
        _subTitle.numberOfLines = 0;
        [self addSubview:_subTitle];
        top = _subTitle.bottom+90;
    }else{
        if ([model.placeHolder isEqualToString:@"Cara frontal del INE"]) {
            _ktpView = [[UIView alloc]initWithFrame:(CGRectMake(space, top, kAppW()-space*2, 140))];
            _ktpView.backgroundColor = WhiteColor();
            _ktpView.layer.shadowColor = Hex_Str_COLOR(@"#B453FF").CGColor;
            _ktpView.layer.shadowOpacity = 0.2;
            _ktpView.layer.shadowOffset = CGSizeMake(0, 2);
            _ktpView.layer.shadowRadius = 8;
            _ktpView.layer.cornerRadius = 8;
            _ktpView.layer.masksToBounds = NO;
            [self addSubview:_ktpView];
            [_ktpView tapAction:^(UIView *sender) {
                @strongify(self);
                [self takePhoto];
            }];
            
            _titleLab = [JMControl createLabelWithFrame:(CGRectMake(space, 30, kAppW()-space*2, 24)) Font:fontWithWeight(17, UIFontWeightMedium) Text:model.title color:HexAlpha_Str_COLOR(@"#222222", 1)];
            [_ktpView addSubview:_titleLab];
            
            _subTitle = [JMControl createLabelWithFrame:(CGRectMake(space, _titleLab.bottom+8, kAppW()-space*2, 20)) Font:fontWithWeight(14, UIFontWeightRegular) Text:model.placeHolder color:HexAlpha_Str_COLOR(@"#555555", 1)];
            [_ktpView addSubview:_subTitle];
            
            _idcardBgImgV = [[UIImageView alloc]initWithFrame:(CGRectMake(_ktpView.width-149, 0, 132, 84))];
            _idcardBgImgV.centerY = _ktpView.height/2;
            [_ktpView addSubview:_idcardBgImgV];
            
            _idcardImgV = [[UIImageView alloc]initWithFrame:(CGRectMake(_ktpView.width-149, 0, 126, 78))];
            _idcardImgV.centerY = _ktpView.height/2;
            _idcardImgV.image = ImageNamed(@"kuang");
            [_ktpView addSubview:_idcardImgV];
            
           
            
            _successImgV = [[UIImageView alloc]initWithFrame:(CGRectMake(0, 0, 32, 32))];
            _successImgV.image = ImageNamed(@"auth_ktp_success");
            _successImgV.center = _idcardImgV.center;
            [_ktpView addSubview:_successImgV];
            top = _ktpView.bottom+(model.topTitle?20:4);
        }else{
            if (top==0) {
                top=16;
            }
            _titleLab = [JMControl createLabelWithFrame:(CGRectMake(space, top, kAppW()-space*2, CalculateLabelHeight(kAppW()-space*2, Font(17), model.title))) Font:Font(14) Text:model.title color:HexAlpha_Str_COLOR(@"#666666", 1)];
            [self addSubview:_titleLab];
            top = _titleLab.bottom + 8;
            
            
            _inputContentV = [[UIView alloc]initWithFrame:(CGRectMake(space, top, kAppW()-space*2, 54))];
            _inputContentV.cornerRadius = 6;
            _inputContentV.backgroundColor = Hex_Str_COLOR(@"#ffffff");
            [self addSubview:_inputContentV];
           
            
            if (model.showArrow) {
                _rightArrowBtn = [JMControl createButtonWithFrame:(CGRectMake(_inputContentV.width-48, 0, 48, _inputContentV.height)) ImageName:@"ahth_arrow" Target:self Action:@selector(rightBtnClick:) font:nil Title:@"    "];
                [_rightArrowBtn setSemanticContentAttribute:UISemanticContentAttributeForceRightToLeft];

                [_inputContentV addSubview:_rightArrowBtn];
                
                self.popupView.authModel = model;
                if ([model.title isEqualToString:@"Nombre"]) {
                    _rightArrowBtn.tag =1;
                    [_rightArrowBtn setImage:ImageNamed(@"auth_book") forState:(UIControlStateNormal)];
                }
                self.popupView.confirmCallback = ^(JMPickerSelectionModel * _Nullable model) {
                    @strongify(self);
                    self.textF.text = model.label;
                    self.inputCallback(model);
                };
                
                self.popupView.confirmDateCallback = ^(NSDate * _Nullable date) {
                    @strongify(self);
                    NSDateFormatter *formatter = [NSDateFormatter new];
                    formatter.dateFormat = @"dd-MM-yyyy";
                    JMPickerSelectionModel *dateModel = JMPickerSelectionModel.new;
                    dateModel.value = [formatter stringFromDate:date];
                    self.textF.text = dateModel.value;
                    self.inputCallback(dateModel);
                };
                if ([model.title isEqualToString:@"Nombre"] ||
                    [model.title isEqualToString:@"Nombre"] ) {
                    
                }else{
                    [self tapAction:^(UIView *sender) {
                        @strongify(self);
                        [JMCommonMethod uploadStatistics:model.pageName actionType:model.actionType parameters:nil];
                        [JMCommonMethod userBehaviorTrack:model.pageName FeatureName:model.featureName Action:(SEL_GET_FOCUS)];

                        [self.popupView popup:[UIApplication sharedApplication].keyWindow edgeInsets:(UIEdgeInsetsZero)];
                        [_popupView setRoundedCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) radii:30];
                    }];
                }
                self.popupView.dismissCompletion = ^{
                    [JMCommonMethod userBehaviorTrack:model.pageName FeatureName:model.featureName Action:(SEL_LOSE_FOCUS)];
                };
                
                right = _rightArrowBtn.width;
            }
            
            _textF = [[UITextField alloc]initWithFrame:(CGRectMake(0, 0, _inputContentV.width-left-right, _inputContentV.height))];
            _textF.placeholder = model.placeHolder;
            _textF.font = fontWithWeight(15, UIFontWeightMedium);
            _textF.delegate = self;
            _textF.textColor = Hex_Str_COLOR(@"#222222");
            
            if ([model.title isEqualToString:@"Nomor rekening"]
                ||[model.title isEqualToString:@"Konfirmasi"]
                ||[model.leftImgName isEqualToString:@"Telepon"]
                ) {
                _textF.returnKeyType = UIKeyboardTypeNumberPad;
            }
            if ([model.title isEqualToString:@"Nombre"]) {
                self.tag = 111;
            }
            if ([model.title isEqualToString:@"Numero"]) {
                self.tag = 222;
            }
            if ([model.title isEqualToString:@"CLABE o tarjeta bancaria"]) {
                _textF.text = model.bankCard;
                _textF.tag = 333;
            }
            if ([model.title isEqualToString:@"Confirmar CLABE o tarjeta bancaria"]) {
                _textF.text = model.bankCard1;
                _textF.tag = 444;
            }
            if ([model.actionType isEqualToString:@"Contact1_Info_Focus"]) {
                _textF.tag = 101;
            }
            if ([model.actionType isEqualToString:@"action_1"]) {
                _textF.tag = 102;
            }
            if ([model.actionType isEqualToString:@"Contact2_Info_Focus"]) {
                _textF.tag = 103;
            }
            if ([model.actionType isEqualToString:@"action_2"]) {
                _textF.tag = 104;
            }
            if (model.showArrow&&![model.title isEqualToString:@"Nombre"]) {
                _textF.enabled = NO;
            }
            
            [_inputContentV addSubview:_textF];
            
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChangeValue:) name:UITextFieldTextDidChangeNotification object:_textF];
            
            top = _inputContentV.bottom;
            
            _LineV = [[UIView alloc]initWithFrame:(CGRectMake(space, top, kAppW()-space*2, 1))];
            _LineV.backgroundColor = Hex_Str_COLOR(@"#EBEBED");
            [self addSubview:_LineV];
            top = _LineV.bottom;
            
            _errorLab = [JMControl createAutoHeightLabelWithOrgin:(CGPointMake(space, top+4)) andWidth:kAppW()-space*2-24*2 Font:Font(12) Text:model.errorMessage color:Hex_Str_COLOR(@"#F53F3F")];
            [self addSubview:_errorLab];
            _errorLab.hidden = YES;
        }
    }
    
    self.width = kAppW();
    self.height = top;
    
}
-(void)updateErrorinfo{
    
    if ([self.model.title isEqualToString:@"CLABE o tarjeta bancaria"]) {
        self.errorLab.hidden = self.model.isMatch;
        self.height = self.model.isMatch?_inputContentV.bottom:_errorLab.bottom;
    }
    if ([self.model.title isEqualToString:@"Confirmar CLABE o tarjeta bancaria"]) {
        self.errorLab.hidden = self.model.isEqual;
        self.height = self.model.isEqual?_inputContentV.bottom:_errorLab.bottom;
    }
}
-(void)takePhoto{
    [[JMBaseRequest sharedInstance]  requestBasePost:BasePostRequestUrl(@"/api/auth/check") params:@{@"authType":@"ADVANCEOCR"} success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        BOOL checkout = dataDic[@"checkResult"];
        if(checkout){
            DDPhotoViewController *vc = [[DDPhotoViewController alloc] init];
            
            @weakify(self);
            vc.imageblock = ^(UIImage *image) {
                @strongify(self);
                //开始请求身份证识别接口
                [JMCommonMethod uploadStatistics:@"VerifyKtp" actionType:@"ID_Front_Request" parameters:nil];

                [JMBaseRequest.sharedInstance requestUploadBasePost:(@"/api/common/oss-upload-positive") params:nil pictures:image success:^(NSDictionary * _Nonnull data) {
                    
                    
                    NSDictionary *tongDunOCRResponseEntity = data[@"tongDunOCRResponseEntity"];
                    NSDictionary *idCardData = tongDunOCRResponseEntity[@"idCardData"];
                    NSString *photoName = data[@"photoName"];
//                    NSString *url = data[@"url"];
                    NSString *fullName = idCardData[@"name"];
                    NSString *idNumber = idCardData[@"nik"];
                    NSString *livenessId = data[@"livenessId"];
                    
                    
                    [JMCommonMethod uploadStatistics:@"VerifyKtp" actionType:@"ID_Front_Result" parameters: @{
                        @"name": fullName?:@"",
                        @"idNum": idNumber?:@"",
                        @"isSuccess": @"true",
                    }];
                    if (data!=nil) {
                        delayOperation(0, ^{
                            [self.idcardImgV setImage:image];
                            self.successImgV.hidden = NO;
                        });
                        self.ktpSuccess(data);
                    }
                    
                } fail:^(NSString * _Nonnull errorMsg) {
                    [JMCommonMethod uploadStatistics:@"VerifyKtp" actionType:@"ID_Front_Result" parameters: @{
                        @"name": @"",
                        @"idNum": @"",
                        @"isSuccess": @"false",
                    }];
                }];
            };
            
            vc.modalPresentationStyle = UIModalPresentationFullScreen;
            [[UIWindow jm_currentViewController] presentViewController:vc animated:YES completion:^{
                [JMCommonMethod uploadStatistics:@"VerifyKtp" actionType:@"ID_Front_Camera_Init" parameters:nil];
            }];
        }else{
            [JMProgressHelper toastInWindowWithMessage:@"Lo sentimos. Aún no es la fecha del evento"];
        }
    } fail:^(NSString * _Nonnull errorMsg) {
        
    }];
}
-(void)check{
    
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(@"/api/auth/livenConfig") params:nil success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(@"/api/auth/check") params:@{@"authType":@"LIVENESS"} success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
            BOOL checkout = [dataDic[@"checkResult"] boolValue];
            if(checkout){
                [JMCommonMethod uploadStatistics:self.model.pageName actionType:@"Liveness_Click" parameters:nil];

                JMSlicenseVC*vc =JMSlicenseVC.new;
                vc.type = 1;
                @weakify(self);
                vc.verifyResultBlock = ^(NSDictionary * _Nonnull dict) {
                    @strongify(self);
                    JMAuthCellModel *model = JMAuthCellModel.new;
                    if (dict[@"livenessId"]) {
                        [self.idcardBgImgV setImage:dict[@"originImage"]];
                        self.idcardBgImgV.layer.borderColor = mainSchemeColor().CGColor;
                        self.idcardBgImgV.contentMode = UIViewContentModeScaleToFill;
                        self.livenessSuccess(dict);
                    }
                };
                [self.viewController.navigationController pushViewController:vc animated:YES];
            }else{
                [JMProgressHelper toastInWindowWithMessage:@"Lo sentimos. Aún no es la fecha del evento"];
            }
        } fail:nil];
    } fail:nil];
}
- (void)showContactController: (void(^)(CNContact *contact))completion {
    self.didSelectedContact = completion;
    delayOperation(0, ^{
        [self.viewController presentViewController:self.contactPickerViewController animated:YES completion:nil];
    });
}

#pragma mark - CNContactPickerDelegate
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
    if (contact.phoneNumbers.count<=1) {
        if (self.didSelectedContact != nil) {
            self.didSelectedContact(contact);
        }
    }else{
        [self.contactPickerViewController dismissViewControllerAnimated:YES completion:^{
            delayOperation(0, ^{
                UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:(UIAlertControllerStyleActionSheet)];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"Cancelación" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                }];
                [alertC addAction:action1];
                
                self.currentContact = contact;
                for (CNLabeledValue<CNPhoneNumber*>*number in contact.phoneNumbers) {
                    NSString *phone = number.value.stringValue;
                    UIAlertAction *action2 = [UIAlertAction actionWithTitle:phone style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        self.selPhoneNumber = phone;
                        self.didSelectedContact(self.currentContact);
                    }];
                    [alertC addAction:action2];
                }
                [self.viewController presentViewController:alertC animated:YES completion:^{}];
            });
        }];
    }
}


- (void)textFieldDidChangeValue:(NSNotification *)notification
{
    UITextField *sender = (UITextField *)[notification object];
    JMPickerSelectionModel*mod = JMPickerSelectionModel.new;
    mod.value = sender.text;
    
    if ([self.model.title isEqualToString:@"CLABE o tarjeta bancaria"]) {
        
        self.model.bankCard = sender.text;
        
        NSString * regex = @"^[0-9]{16}$|^[0-9]{18}";
          
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        BOOL isMatch = [pred evaluateWithObject: sender.text];
        if (isMatch) {
            self.model.isMatch = YES;
        }else{
            self.model.isMatch = NO;
        }
    }
    if ([self.model.title isEqualToString:@"Confirmar CLABE o tarjeta bancaria"]) {
        self.model.bankCard1 = sender.text;

        UIView *supV = self.superview;
        UITextField *banTf = [supV viewWithTag:333];
        BOOL isMatch = [sender.text isEqualToString:banTf.text];

        if (isMatch) {
            self.model.isEqual = YES;
        }else{
            self.model.isEqual = NO;
        }
    }
    if (self.inputCallback) {
        self.inputCallback(mod);
    }
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    [JMCommonMethod uploadStatistics:self.model.pageName actionType:self.model.actionType parameters:nil];
    
    [JMCommonMethod userBehaviorTrack:self.model.pageName FeatureName:self.model.featureName Action:(GET_FOCUS)];

}
-(void)textFieldDidEndEditing:(UITextField *)textField{
    [JMCommonMethod userBehaviorTrack:self.model.pageName FeatureName:self.model.featureName Action:(LOST_FOCUS)];
}

-(void)rightBtnClick:(UIButton *)sender{
    if (sender.tag) {
        UITextField *name1TF = [self.viewController.view viewWithTag:101];
        UITextField *tel1TF = [self.viewController.view viewWithTag:102];
        UITextField *name2TF = [self.viewController.view viewWithTag:103];
        UITextField *tel2TF = [self.viewController.view viewWithTag:104];
        [self showContactController:^(CNContact *contact) {
            if (contact.phoneNumbers.count>1) {
                NSString *name = [NSString stringWithFormat:@"%@%@%@%@%@", contact.namePrefix, contact.givenName, contact.middleName, contact.familyName,contact.nickname, contact.nameSuffix];
                NSString *orgizionName = contact.organizationName;
                if ([name isEqualToString:@""]&&orgizionName!=nil) {
                    name = orgizionName;
                }
                if ([self.model.actionType isEqualToString:@"Contact1_Info_Focus"]) {
                    name1TF.text = name;
                    tel1TF.text = self.selPhoneNumber;
                }else{
                    name2TF.text = name;
                    tel2TF.text = self.selPhoneNumber;
                }
                JMPickerSelectionModel*mod = JMPickerSelectionModel.new;
                mod.value = name;
                mod.label = self.selPhoneNumber;
                self.inputCallback(mod);
            }else{
                NSString *name = [NSString stringWithFormat:@"%@%@%@%@%@", contact.namePrefix, contact.givenName, contact.middleName, contact.familyName, contact.nameSuffix];
                if ([self.model.actionType isEqualToString:@"Contact1_Info_Focus"]) {
                    name1TF.text = name;
                }else{
                    name2TF.text = name;
                }
                
                NSArray<CNLabeledValue<CNPhoneNumber*>*>  *phoneNumbers = contact.phoneNumbers;
                if (phoneNumbers != nil) {
                    CNLabeledValue<CNPhoneNumber *> *obj = phoneNumbers.firstObject;
                    if ([self.model.actionType isEqualToString:@"Contact1_Info_Focus"]) {
                        tel1TF.text = obj.value.stringValue;
                    }else{
                        tel2TF.text = obj.value.stringValue;
                    }
                    JMPickerSelectionModel*mod = JMPickerSelectionModel.new;
                    mod.value = name;
                    mod.label = obj.value.stringValue;
                    self.inputCallback(mod);
                }
            }
        }];
        return;
    }
   
    [JMCommonMethod uploadStatistics:self.model.pageName actionType:self.model.actionType parameters:nil];
    [self.popupView popup:[UIApplication sharedApplication].keyWindow edgeInsets:(UIEdgeInsetsZero)];
    [_popupView setRoundedCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) radii:30];
    
}
- (JMPickerSelectionView *)popupView {
    if (!_popupView) {
        self.popupView = [JMPickerSelectionView new];
        [_popupView.widthAnchor constraintEqualToConstant: kScreenWidth].active = YES;
        _popupView.backgroundColor = [UIColor whiteColor];
    }
    return _popupView;
}
- (CNContactPickerViewController *)contactPickerViewController {
    if (!_contactPickerViewController) {
        self.contactPickerViewController = [[CNContactPickerViewController alloc] init];
        _contactPickerViewController.delegate = self;
    }
    return _contactPickerViewController;
}
@end
